import { Observable, Subject, Observer } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable()
export class WebSocketService {
    public a01: any;
    public create(url: string): Subject<MessageEvent> {
        const ws = new WebSocket(url);
        ws.onopen = function () {
            // ws.send(nodeid);
        };
        // 如果想要断开websocket连接，调用websocket.service.ts的a01函数即可。
        // this.a01 = function() {
        //   ws.close();
        //   console.log("websocket01已经断开连接");
        // };
        const observable = Observable.create(
            (obs: Observer<MessageEvent>) => {
                ws.onmessage = obs.next.bind(obs);
                ws.onerror = obs.error.bind(obs);
                ws.onclose = obs.complete.bind(obs);
                return ws.close.bind(ws);
            });
        const observer = {
            next: (data: Object) => {
                if (ws.readyState === WebSocket.OPEN) {
                    ws.send(data);
                }
            }
        };
        return Subject.create(observer, observable);
    }
}
